use solutiont5::PERSON_TYPE;

pub fn retire_time(time: &str, tp: &str) -> String {
    let birth: Vec<_> = time.split('-').map(|x| x.parse::<u16>().unwrap()).collect();
    let info = &PERSON_TYPE[tp];
    let mut retirement_year = birth[0] + info.origin_retirement_age();
    let mut retirement_month = birth[1];
    let mut retirement_age = info.origin_retirement_age() as f64;
    let mut delay_month = 0;
    for police in info.polices() {
        let impl_date: Vec<_> = police
            .policy_impl_date()
            .split('-')
            .map(|x| x.parse::<u16>().unwrap())
            .collect();
        let var_age = police.target_age() - info.origin_retirement_age();
        let duration = var_age * police.cycle_time() / police.delay_amount();
        if retirement_year < impl_date[0]
            || (retirement_year == impl_date[0] && retirement_month < impl_date[1])
        {
            continue;
        } else if birth[0] >= impl_date[0] - info.origin_retirement_age() + duration {
            retirement_year += var_age;
            retirement_age += var_age as f64;
            delay_month += var_age * 12;
        } else {
            let months = (((retirement_year - impl_date[0]) * 12 + retirement_month) as f64
                / police.cycle_time() as f64)
                .ceil() as u16
                * police.delay_amount();
            delay_month += months;
            retirement_year += months / 12;
            retirement_month += months % 12;
            if retirement_month > 12 {
                retirement_month = retirement_month % 12;
                retirement_year += 1;
            }
            retirement_age += months as f64 / 12.0;
        }
    }
    if retirement_age.floor() == retirement_age {
        format!(
            "{}-{:02},{},{}",
            retirement_year, retirement_month, retirement_age as i64, delay_month
        )
    } else {
        format!(
            "{}-{:02},{:.2},{}",
            retirement_year, retirement_month, retirement_age, delay_month
        )
    }
}
